interface MessageEventData {
  id: string; // 文件唯一 ID
  arrayBuffer: ArrayBuffer;
  password: string;
  filename: string;
}
self.addEventListener(
  "message",
  async (e: globalThis.MessageEvent<MessageEventData>) => {
    const { password, arrayBuffer, id } = e.data;
    const decrypt = await decryptFile(arrayBuffer, password);
    postMessage({ ...decrypt, id });
  }
);

async function decryptFile(encryptedPackage: ArrayBuffer, password: string) {
  const decoder = new TextDecoder();
  const encoder = new TextEncoder();

  // 1. 密码派生为 256 位 AES 密钥
  const passwordData = encoder.encode(password);
  const hashBuffer = await crypto.subtle.digest("SHA-256", passwordData);
  const key = await crypto.subtle.importKey(
    "raw",
    hashBuffer,
    { name: "AES-GCM" },
    false,
    ["decrypt"]
  );

  const packageView = new Uint8Array(encryptedPackage);
  try {

  // 2. 读取元数据长度
  const metaLengthView = packageView.slice(0, 4);
  const metaLength = new Uint32Array(metaLengthView.buffer)[0]!;

  // 3. 读取元数据
  const metaBuffer = packageView.slice(4, 4 + metaLength);
  const metaStr = decoder.decode(metaBuffer);
  const meta = JSON.parse(metaStr);
  // 4. 获取 IV
  const iv = new Uint8Array(meta.iv);

  // 5. 读取加密内容
  const encryptedBuffer = packageView.slice(4 + metaLength).buffer;

    const decryptedBuffer = await crypto.subtle.decrypt(
      { name: "AES-GCM", iv },
      key,
      encryptedBuffer
    );
    return {
      filename: meta.filename,
      ext: meta.ext,
      arrayBuffer: decryptedBuffer,
      status:'finish'
    };
  } catch {
    return {
        status:'fail'
    }
  }
  // 6. 解密
}
